﻿using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;

namespace DBUtil.Provider.Oracle;

public partial class OracleAccess : DBAccess
{
    #region 使用SqlBulkCopy批量插入数据
    public override async Task BulkCopyAsync(DataTable dt, string tableName = null, int timeoutSeconds = 60 * 30, int notifyAfter = 0, Func<long, Task<bool>> callBack = null, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(tableName)) tableName = dt.TableName;
        if (string.IsNullOrWhiteSpace(tableName)) throw new Exception("必须指定要目的表名!");
        OracleBulkCopy sbc = null;
        if (IsSession) sbc = new OracleBulkCopy((OracleConnection)CurrentConnection);
        else sbc = new OracleBulkCopy((OracleConnection)GetNewConnection());

        sbc.BulkCopyTimeout = timeoutSeconds;
        sbc.DestinationTableName = tableName;
        sbc.NotifyAfter = notifyAfter;
        if (callBack != null) sbc.OracleRowsCopied += async (object sender, OracleRowsCopiedEventArgs e) =>
        {
            e.Abort = await callBack(e.RowsCopied);
        };
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sbc.ColumnMappings.Add(new OracleBulkCopyColumnMapping(i, dt.Columns[i].ColumnName));
        }
        //没有异步方法?
        sbc.WriteToServer(dt);
    }
    #endregion
}
